package com.jzo2o.orders.manager.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.orders.manager.service.IOrdersCanceledService;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 11394
 * @version 1.0
 * @description: TODO
 * @date 2024/8/29 21:09
 */
@Component
public class TradeStatusListener {

    @Resource
    IOrdersCreateService iOrdersCreateService;
    @Resource
    IOrdersManagerService iOrdersManagerService;


    /**
    * @description
    * @author Gaosir
    * @return * @return: null
    * 更新支付结果
     * 支付成功
    * @date 2024/8/29 21:09
    */
    @RabbitListener(bindings = @QueueBinding(
            //队列
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            //交换机
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE,type = ExchangeTypes.TOPIC),
            //路由key
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listentradppage(String msg){

        //将msg转为java对象
        List<TradeStatusMsg> tradeStatusMsgs = JSON.parseArray(msg, TradeStatusMsg.class);

        //只处理家政服务的订单且是支付成功的
        List<TradeStatusMsg> msgs = tradeStatusMsgs.stream().filter(s -> s.getStatusCode().equals(TradingStateEnum.YJS.getCode()) && s.getProductAppId().equals("jzo2o.orders")).collect(Collectors.toList());

        if(CollUtil.isEmpty(msgs)){
            return;
        }

        //修改订单状态
        msgs.forEach(m->iOrdersManagerService.pageSuccess(m));
    }

}
